<template>
	<view class="yz">
		<!-- 两个输入框 -->
		<view class="inputBox">
			<text class="cuIcon-people"></text>
			<input class="uni-input-input" type="text" placeholder="请输入手机号" v-model="account" maxlength="11" />
			<text class="cuIcon-people" style="visibility: hidden;"></text>
		</view>
		<view class="inputBox" v-if='!IsCodeLogin'>
			<text class="cuIcon-lock"></text>
			<!-- BUG 加上这个uni-input-input类名 不然样式炸 -->
			<input class="uni-input-input" :type="init.HidePwd ? 'password' : 'text'" placeholder="请输入密码" v-model="pwd"
			 maxlength="16" />
			<text class="cuIcon-attention" @click="ShowHidePwd"></text>
		</view>
		<!-- 忘记密码和注册账号 -->
		<view class="other mt30">
			<text class="fo-gray fo-24" @click="onResetPwd">忘记密码?</text>
			<text class="fo-24" @click="$pub.naviTo('/pages/other/register/index')">注册账号</text>
		</view>
		<!-- 登录按钮 -->
		<view class="flex flex-col wid1p ali-cen relative mt40">
			<button class="cu-btn-1 fo-black" :class="{iSUseCurrent:!IsCodeLogin,absuTop50:IsCodeLogin}" @click="onLogin">{{com_accoundLogin}}</button>
			<button class="cu-btn-2 fo-black" :class="{iSUseCurrent:IsCodeLogin,absuTop0:IsCodeLogin}" @click="goSMSLogin">{{com_CodeLogin }}</button>
		</view>


		<!-- 滑块验证 -->
		<slider-verify :isShow="sliderVerifyFLag" @touchSliderResult="verifyResult" ref="verifyElement"></slider-verify>
	</view>
</template>

<script>
	// 非对称加密
	// #ifdef H5
	import JSEncrypt from 'jsencrypt/bin/jsencrypt'
	// #endif
	// #ifdef APP-PLUS
	import JSEncrypt from '@/common/components/jsencrypt-Rsa/jsencrypt/jsencrypt.min.js'
	// #endif
	
	// MD5加密
	import MD5 from '@/common/Tools/md5.js'

	import sliderVerify from '@/components/sliderVerify/index.vue'
	import {
		API$login
	} from '../../../../common/API/other.js';
	import {
		API$GetUserinfo
	} from '../../../../common/API/home.js';


	
	export default {
		name: '',
		components: {
			sliderVerify
		},
		data() {
			return {
				init: {
					HidePwd: true
				},
				account: '',
				pwd: '',
				IsCodeLogin: false, // 是否是验证码登录

				sliderVerifyFLag: false //滑块验证
			};
		},
		computed: {
			com_accoundLogin() {
				return this.IsCodeLogin ? '账号密码登录' : "登录"
			},
			com_CodeLogin() {
				return this.IsCodeLogin ? "获取验证码" : "验证码登录"
			}
		},
		async mounted() {
			
			//  手动注册
			// let {msg} = await this.$HuanxinIM.Register({
			// 	user:'d81cd5415f9458be01a7d88573e88379'  ,// 这边是用洋盘用户的唯一标识_id
			// 	pwd:MD5('BC72AD5257B03924477B7BBB3056A1A3')
			// })
			// // 注册成功~
			// if(msg==='ok'){
			// 	console.log('IM注册成功~')
			// }else{
			// 	this.$pub.Toast('IM注册失败~')
			// }
			
			
		},
		methods: {
			// 显示或隐藏密码
			ShowHidePwd() {
				this.init.HidePwd = !this.init.HidePwd;
			},
			// 短信验证码登录
			goSMSLogin() {
				if (this.com_CodeLogin === '验证码登录') {
					return this.IsCodeLogin = true
				}

				if (!this.$verify.PhoneFormat(this.account)) {
					return this.$pub.Toast('手机号码格式有误')
				}
				this.sliderVerifyFLag = true


			},
			// 重设密码
			onResetPwd() {
				this.$pub.naviTo('/pages/other/ResetPwd/index')
			},
			// 滑块验证结果回调函数
			verifyResult(res) {
				this.sliderVerifyFLag = false;
				if (res) { //校验通过
					this.$pub.naviTo(`/pages/other/SMSCodeLogin/index?account=${this.account}`)
				} else {
					// 校验失败,点击关闭按钮
					this.$pub.Toast('您取消了滑块验证！')
				}
			},
			/******************数据处理部分*******************************/
			// 账号密码登录
			async onLogin() {
				let $JSEncrypt = new JSEncrypt()
				$JSEncrypt.setPublicKey(this.$pub.pubKey()) // 设置公钥

				if (this.com_accoundLogin === '账号密码登录') {
					return this.IsCodeLogin = false
				}

				if (!this.account || !this.pwd) return this.$pub.Toast('账号密码不能为空~')
				
				
				
				uni.showLoading({
					title: '登录中',
					mask: true
				});
				let res = await API$login({
					account: this.account,
					pwd: $JSEncrypt.encrypt(this.pwd)
				});
				uni.hideLoading();
				this.$pub.Toast(res.msg);
				if (res.code == 200) {
					
					this.$pub.setStorageSync('Token', res.Token); // 添加token
					this.$pub.setStorageSync('Sts', res.Sts); // 添加sts临时权限
					let res1 = await API$GetUserinfo();
					if (res1.code == 200) {
						this.$pub.setStorageSync('UserInfo', res1.result); // 添加个人信息

						
						
						try{
							this.$HuanxinIM.close()
						}catch(e){
							console.log('初始化登录IM',e)
						}finally{
							setTimeout(async()=>{
								console.log('登录IM')
								// 登录IM
								let {msg,data} = await this.$HuanxinIM.Login({
									user:res1.result._id,
									pwd: MD5(this.pwd)
								})
								if(msg==='fail'){
									this.$pub.Toast('账号密码错误~',data)
									this.$pub.reLaunch('/pages/other/login/index')
								}
								console.log(data)
								this.$pub.setStorageSync('HuanXinInfo',data)
							},2500)
						}
						
						
						
						
						
						// 取账号缓存
						let oldAccountList = this.$pub.getStorageSync('AcclountList')
						let indexS = oldAccountList ? oldAccountList.findIndex(i => i._id === res1.result._id) : -1
						// 账号缓存不存在
						if (!oldAccountList || indexS === -1) {
							oldAccountList = oldAccountList ? oldAccountList : [],
								oldAccountList ? oldAccountList.forEach(i => i.IsCheck = false) : ""
							let AccontJson = [{
								UpdateDate: new Date(),
								Token: res.Token,
								IsCheck: true, // 当前选中的登录的账号
								Account: res1.result.account,
								Nickname: res1.result.Nickname,
								Avatar: res1.result.avatar,
								_id: res1.result._id,
						
								Info: res1.result
							}]
							this.$pub.setStorageSync('AcclountList', [...oldAccountList, ...AccontJson]); // 添加账号缓存
							// 账号缓存存在 覆盖掉旧数据
						} else {
							oldAccountList.forEach(i => i.IsCheck = false)
						
							// console.warn('我是覆盖的逻辑', oldAccountList, oldAccountList[indexS])
							oldAccountList[indexS].UpdateDate = new Date();
							oldAccountList[indexS].Token = res.Token;
							oldAccountList[indexS].Nickname = res1.result.Nickname;
							oldAccountList[indexS].Avatar = res1.result.avatar;
							oldAccountList[indexS].IsCheck = true;
						
							oldAccountList[indexS].Info = res1.result;
							this.$pub.setStorageSync('AcclountList', [...oldAccountList]); // 添加账号缓存
						}
						
						
					}
					this.$pub.swiTab('/pages/index/index');
				}
			}
		}
	};
</script>

<style lang="less" scoped>
	@import './index.less';
</style>
